import {
  getUserInfo,checkVersion
} from "@/api/api";
import router from '@/router'
import { Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: "",
    userObj: null,
    baseUrl: process.env.VUE_APP_BASE_API,
    caipinOrder:['米饭套餐','红汤抄手','红汤小面','蛋炒饭','家常河粉','酸萝卜鸭掌汤饭','猪蹄汤饭','炸酥肉','炸香蕉','南瓜饼','油炸鳕鱼排','黄金糕','鸡米花','卤香炸鸡腿','卤凤爪','咖喱鱼蛋','辣豆花','甜豆花','酸萝卜鸭掌汤','猪蹄汤','小汤圆','凉拌土豆','银耳糯米羮','枸杞银耳汤','椰汁西米露']
  }
}

const state = getDefaultState()

const mutations = {
  setToken(state, token) {
    state.token = token
  },
  setUserObj(state, obj) {
    state.userObj = {
      ...obj
    }
  },
  logout(state, obj) {
    localStorage.removeItem("token");
    state.userObj = null
    router.push("/login")
  }
}

const actions = {
  logout({
    commit,
    state
  }) {
    setTimeout(()=>{
      localStorage.clear()
    },500)
    router.push("/login")
  },
  getUserObj({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.code == 200) {
          commit("setUserObj", res.data.user)
          if(!res.data.user.level){
            Message("你好，请先完善楼层信息!")
            router.push("/person-center/setting")
          }
        }
        resolve(res)
      })

    }).catch(error => {
      reject(error)
    })
  },
  checkVersion({
    commit,
    state
  }) {
    checkVersion(this.state.food.userObj).then(res => {
      if(res.code == -1){
        //版本号不一致，需要提示并且退出登录
        // this.$message.error(res.msg)
        commit("logout", "")
        alert(res.msg)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
